package com.sgb.kjwl.view.ui.activity.manage;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.google.android.material.tabs.TabLayout;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityShopInfoForConpamyTradesBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.ManageEvent;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopCompanyInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.manage.ShopCompanyManageFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickCompanyDetailFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopJcChildFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopMachineChildFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopMaterialChildFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopTdChildFragment;
import com.sgb.kjwl.viewmodel.manage.ShopInfoForCompanyTradesModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

import static com.swgk.core.event.EventConstant.EVENT_SHOP_INFO_FOR_COMPANY_TRADES_JUMP;

@Route(path = AppRouteConstant.WEB_SHOPINFO)
public class ShopInfoForCompanyTradesActivity extends AppActivity {
    private ActivityShopInfoForConpamyTradesBinding binding;
    boolean userFocusCompanyStatus;
    @Inject
    ShopInfoForCompanyTradesModel viewModel;
    boolean state;
    private String[] mTabName = new String[]{"商品", "租赁经营", "招采经营", "集采管理", "工程工队", "企业经营"};
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private String shopId;
    private String companyNo;
    private int mInitPosition;
    private int childPosition;
    @Autowired(name = "id")
    public  String ids;
    @Autowired(name = "companyNo")
    public   String companyNos;
    @Autowired(name = "position")
    public   int positions;
    @Autowired(name = "childPosition")
    public   int childPositions;
    @Autowired(name = "isARouter")
    public   boolean isARouter;

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).enterpriseManageModule(new EnterpriseManageModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    public static void startAct(Context context, String companyId, String companyNo, int position, int childPosition) {
        Intent intent = new Intent(context, ShopInfoForCompanyTradesActivity.class);
        intent.putExtra("id", companyId);
        intent.putExtra("companyNo", companyNo);
        intent.putExtra("position", position);
        intent.putExtra("childPosition", childPosition);
        context.startActivity(intent);
    }

    public static void startAct(Context context, String companyId, String companyNo, int position, int childPosition,boolean follow) {
        Intent intent = new Intent(context, ShopInfoForCompanyTradesActivity.class);
        intent.putExtra("id", companyId);
        intent.putExtra("companyNo", companyNo);
        intent.putExtra("position", position);
        intent.putExtra("childPosition", childPosition);
        intent.putExtra("follow", follow);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        if (isARouter){
            shopId = ids;
            companyNo = companyNos;
            mInitPosition = positions;
            childPosition = childPositions;
        }else {
            shopId = getIntent().getStringExtra("id");
            companyNo = getIntent().getStringExtra("companyNo");
            state = getIntent().getBooleanExtra("follow",false);
            mInitPosition = getIntent().getIntExtra("position", 0);
            childPosition = getIntent().getIntExtra("childPosition", 0);
        }
        binding = DataBindingUtil.setContentView(ShopInfoForCompanyTradesActivity.this, R.layout.activity_shop_info_for_conpamy_trades);
        binding.setViewModel(viewModel);
        viewModel.getuserFocusCompanyStatus(shopId);
        binding.layoutAttention.setOnClickListener(this);
        binding.shopInfoLayout.setOnClickListener(this);
        binding.shopMessage.setOnClickListener(this);
    }

    @Override
    protected void init() {
        SharedPreferenceUtil.init(this);
        Map<String, Object> map = new HashMap<>();
        map.put("id", shopId);
        viewModel.shopDetail(map);
        viewModel.getShopImInfo(shopId);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_attention:
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    MToast.showToast(this, "您还没有登录，请先登录");
                    return;
                }
                viewModel.userFocusCompany(companyNo);
                break;
            case R.id.shop_info_layout:
                ShopCompanyInfoActivity.start(this, viewModel.shopInfoEntity.get());
                break;
            case R.id.shop_message:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    IMUtils.getInstance().buildSingleTalking(viewModel.shopImAccount.get());
//                    MToast.showToast(ShopInfoForCompanyTradesActivity.this,"功能暂未开放");
                    //NimUIKit.startP2PSession(ShopInfoForCompanyTradesActivity.this, viewModel.shopImAccount.get());
                }
                break;
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(ShopInfoForCompanyTradesActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });
            } else {
                //有权限
                openLoginPage();
            }
        } else {
            VerificationCodeLoginActivity.start(this, EVENT_SHOP_INFO_FOR_COMPANY_TRADES_JUMP);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(ShopInfoForCompanyTradesActivity.this, EVENT_SHOP_INFO_FOR_COMPANY_TRADES_JUMP);
                }
            }
        }, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code == 1000) {
                OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                oneKeyLoginEntity.setPlateform("Android");
                viewModel.oneKeyLogin(oneKeyLoginEntity);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void setData() {
        if (viewModel.shopInfoEntity.get().getAuthTime() != null) {
            binding.shopTime.setText("入驻日期：" + DateUtils.timestampToDate(Long.parseLong(viewModel.shopInfoEntity.get().getAuthTime())));
        }
        if (TextUtils.isEmpty(companyNo)){
            companyNo = viewModel.shopInfoEntity.get().getCompanyNo();
        }
        RequestOptions options = new RequestOptions().placeholder(R.mipmap.shop_img)//图片加载出来前，显示的图片
                .error(R.mipmap.shop_img);//图片加载失败后，显示的图片
        String url = TextUtils.isEmpty(viewModel.shopInfoEntity.get().getLogo()) ? "" : viewModel.shopInfoEntity.get().getLogo();
        Glide.with(this).load(url).apply(options)//异常时候显示的图片
                .into((binding.shopImg));
        ArrayList<Fragment> mFragments = new ArrayList<>();
        mFragments.add(ShopMaterialChildFragment.newInstance(shopId));
        mFragments.add(ShopMachineChildFragment.newInstance(companyNo,"", childPosition));
        mFragments.add(PickCompanyDetailFragment.newInstance(viewModel.shopInfoEntity.get().getCompanyNo()));
        mFragments.add(ShopJcChildFragment.newInstance(companyNo));
        mFragments.add(ShopTdChildFragment.newInstance(shopId));
        //企业经营
        mFragments.add(ShopCompanyManageFragment.newInstance(companyNo, childPosition));
        SlidingFragmentPagerAdapter mAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTabName);
        binding.viewpager.setAdapter(mAdapter);
        binding.viewpager.setOffscreenPageLimit(3);
        binding.tablayout.setupWithViewPager(binding.viewpager);
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        binding.viewpager.setCurrentItem(mInitPosition);
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
        if (state != userFocusCompanyStatus){
            EventBus.getDefault().postSticky(ManageEvent.make().setMessageTag(EventConstant.EVENT_MANAGE_MAP_FOLLOW));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_SHOP_INFO_FOR_COMPANY_TRADES_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void setUserFocusCompanyStatus() {
        setUserFocusCompanyStatus(!userFocusCompanyStatus);
    }


    public void setUserFocusCompanyStatus(boolean data) {
        if (data) {
            binding.layoutAttention.setBackgroundResource(R.drawable.bgg_lg);
            binding.attentionImg.setImageResource(R.mipmap.attention_unnomal);
            binding.tvAttention.setTextColor(getResources().getColor(R.color.alertdialog_gray));
            binding.tvAttention.setText("已关注");
        } else {
            binding.layoutAttention.setBackgroundResource(R.drawable.bgw_lb);
            binding.attentionImg.setImageResource(R.mipmap.attention_nomal);
            binding.tvAttention.setText("关注");
            binding.tvAttention.setTextColor(getResources().getColor(R.color.alertdialog_blue));
        }
        userFocusCompanyStatus = data;
    }
}
